<template>
  <div class="panoramadiv" id="panorama"></div>
  <div
    style="
      z-index: 7;
      position: absolute;
      top: 10px;
      right: 50%;
      background-color: #0009;
      padding: 5px 15px 5px 15px;
      border-radius: 5px;
    "
  >
    拍摄时间：{{ imgtime }}
  </div>
  <div
    style="
      z-index: 7;
      position: absolute;
      top: 10px;
      right: 10px;
      width: 100px;
      height: 100px;
      border: 1px solid #fff;
    "
  >
    <el-image
      style="width: 100px; height: 100px"
      :src="earthStore.panoramaurl_upload"
      :preview-teleported="true"
      :hide-on-click-modal="true"
      :zoom-rate="1.2"
      :preview-src-list="[earthStore.panoramaurl_upload]"
      :initial-index="4"
      fit="cover"
    >
      <template #placeholder>
        <div class="image-slot">Loading<span class="dot">...</span></div>
      </template>
      <template #error>
        <div class="image-slot">
          <el-icon><icon-picture /></el-icon>
        </div>
      </template>
    </el-image>
  </div>
  <el-button
    type="info"
    size="default"
    @click="closePanorama();earthStore.showPanorama = false;"
    circle
    style="z-index: 7; position: absolute; top: 100px; left: 3px"
  >
    <el-icon color="#fff" class="no-inherit">
      <svg
        t="1693877052067"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="3992"
        width="200"
        height="200"
      >
        <path
          d="M700.371228 394.525472 174.028569 394.525472l255.952416-227.506551c12.389168-11.011798 13.505595-29.980825 2.492774-42.369993-11.011798-12.386098-29.977755-13.506619-42.367947-2.492774L76.425623 400.975371c-6.960529 5.496178-11.434423 14.003945-11.434423 23.561625 0 0.013303 0.001023 0.026606 0.001023 0.039909 0 0.01228-0.001023 0.025583-0.001023 0.037862 0 0.473791 0.01535 0.946558 0.037862 1.418302 0.001023 0.016373 0.001023 0.032746 0.001023 0.049119 0.39295 8.030907 3.992941 15.595186 10.034541 20.962427l315.040163 280.028764c5.717212 5.083785 12.83533 7.580652 19.925818 7.580652 8.274454 0 16.514115-3.403516 22.442128-10.07445 11.011798-12.387122 9.896394-31.357172-2.492774-42.367947l-256.128425-227.665163 526.518668 0c109.219517 0 198.075241 88.855724 198.075241 198.075241s-88.855724 198.075241-198.075241 198.075241L354.324888 850.696955c-16.57449 0-30.011524 13.437034-30.011524 30.011524s13.437034 30.011524 30.011524 30.011524l346.046341 0c142.31631 0 258.098289-115.783003 258.098289-258.098289S842.686515 394.525472 700.371228 394.525472z"
          fill=""
          p-id="3993"
        ></path>
      </svg>
    </el-icon>
  </el-button>
</template>
<script setup lang="">
import "pannellum";
import "pannellum/build/pannellum.css";
import { onMounted, ref, onUnmounted } from "vue";
import { useEarthStore } from "@/stores/earth";
import { httpRequest } from "@/api/httpRequest";
import * as turf from "@turf/turf";

import _ from "lodash";

const earthStore = useEarthStore();

let pannelviewer = "";

let imgtime = ref("-");

onUnmounted(() => {
  pannelviewer.destroy();
});

onMounted(() => {
  window.quanjingcom.exposed.sv()
  loadData();
  // earthview();
  addEvent();
});


let pointE = "";
let imgpoint = [];

function closePanorama(params) {
  viewer.entities.remove(pointE);
  viewer.scene.postRender.removeEventListener(pre)
  viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); 
}

let pre = (scene, time) => {
    if (pannelviewer != "") {
      viewer.camera.lookAt(
        Cesium.Cartesian3.fromDegrees(imgpoint[0] * 1.0, imgpoint[1] * 1.0, 2),
        new Cesium.HeadingPitchRange(Cesium.Math.toRadians(pannelviewer.getYaw() + 180), Cesium.Math.toRadians(pannelviewer.getPitch() > 0 ? 0 : pannelviewer.getPitch()), 100)
        // new Cesium.HeadingPitchRange(Cesium.Math.toRadians(pannelviewer.getYaw()), Cesium.Math.toRadians(pannelviewer.getPitch() + 180), 100)
      );
    }
  }

function addEvent(params) {
  viewer.scene.postRender.addEventListener(pre);
}

function earthview(params) {
  pointE = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(imgpoint[0] * 1.0, imgpoint[1] * 1.0, 2),
    point: {
      pixelSize: 20,
      color: Cesium.Color.YELLOW.withAlpha(0.8), // 半透明
      // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 贴地
      // disableDepthTestDistance: Number.POSITIVE_INFINITY, // 始终可见（不被地形遮挡）
      // // 闪烁效果
      // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
      // translucencyByDistance: new Cesium.NearFarScalar(1000, 1, 5000, 0)
    },
  });

  // viewer.camera.lookAt(
  //   pointE,
  //   new Cesium.HeadingPitchRange(0, -0.5, 100)
  // );
}

function loadData() {
  {
    // 中心点图片初始配置
    let options = {
      default: {
        firstScene: "mainimg",
        autoLoad: true,
        compass: true,
      },
      scenes: {
        mainimg: {
          type: "equirectangular",
          panorama: "" + earthStore.panoramaurl,
          autoLoad: true,
          showControls: true,
          hotSpots: [],
        },
      },
    };

    // pannelviewer = pannellum.viewer("panorama", options);
    // viewer.setYaw(180);

    // return

    // wfs 查询链接
    // http://192.168.211.130:8888/zxntest/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=zxntest%3APOINT&maxFeatures=50&outputFormat=application%2Fjson&BBOX=113.55833798646927,34.80803757905961,113.55887979269028,34.808579385280616

    // 获取bbox
    // earthStore.panoramaurl.split("-")[0].split(",")

    let path_arr = earthStore.panoramaurl.split("/")[
      earthStore.panoramaurl.split("/").length - 1
    ];
    let pathname_arr = path_arr.split("-");

    //获取周围15m bbox
    let posarr = path_arr.split("-")[0].split(",");
    var point = turf.point([posarr[0] * 1, posarr[1] * 1]);
    imgpoint = posarr;
    earthview();
    var buffered = turf.buffer(point, 11, { units: "meters", steps: 1 });
    var bbox = turf.bbox(buffered);

    // // console.log(bbox);
    // // posarr
    // console.log(posarr.join(","));

    // return

    httpRequest
      .get(
        // "/jiejing/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif%3Ajuhetuceng&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
          "/jiejing/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif%3Ajiejing&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
          bbox.join(",")
      )
      .then(res => {
        // 计算角度
        //
        let cindex = -1;

        res.features.map((item, index) => {
          if (item.geometry.coordinates[0] == posarr[0] * 1) {
            cindex = index;
          }
        });

        console.log(res);

        var point1 = turf.point([posarr[0] * 1, posarr[1] * 1]);
        var point2 = turf.point([102.865569, 34.089941]);

        let headingmain = 0

        delete res.features[cindex];
        res.features.map((item, index) => {
          point2 = turf.point(item.geometry.coordinates);
          var bearing = turf.bearing(point1, point2);

          let sceneid = "scene" + index;
          let heading = pathname_arr[pathname_arr.length - 2] * 1;

          heading = (heading * 180) / Math.PI;
          headingmain = heading

          options.scenes.mainimg.hotSpots.push({
            pitch: 0,
            yaw: -bearing + heading,
            type: "scene",
            text: "",
            sceneId: sceneid,
          });

          let itempath =
            "/juhetuceng/" +
            item.id.split("_")[0] +
            "_" +
            item.id.split("_")[1] +
            "/" +
            item.properties.name;

          options.scenes[sceneid] = {
            type: "equirectangular",
            panorama: itempath,
            // "113.51081025235848%2C34.808792394723255-09028900122208121351021105Q-06348.jpg",
            autoLoad: true,
            showControls: true,
          };
          console.log(bearing);
          console.log(heading);
          console.log(bearing + heading);
        });
        pannelviewer = pannellum.viewer("panorama", options);
        // pannelviewer.setYaw(+headingmain)
      });

    // pannelviewer.animatefinished((a) => {
    //   console.log(a);
    // })

    console.log(pannelviewer);

    setInterval(() => {
      const pitch = pannelviewer.getPitch(); // 俯仰角（垂直角度）
      const yaw = pannelviewer.getYaw(); // 偏航角（水平角度）
      const hfov = pannelviewer.getHfov(); // 视野范围

      console.log(
        `实时角度: pitch=${pitch.toFixed(2)}°, yaw=${yaw.toFixed(
          2
        )}°, hfov=${hfov.toFixed(2)}°`
      );
    }, 500);

    // let options = {
    //   type: "equirectangular",
    //   panorama: "http://127.0.0.1:8000/15/" + earthStore.panoramaurl,
    //   // "113.51081025235848%2C34.808792394723255-09028900122208121351021105Q-06348.jpg",
    //   autoLoad: true,
    //   showControls: true,
    //   hotSpots: [
    //     {
    //       pitch: 14.1,
    //       yaw: -11.4,
    //       type: "scene",
    //       text: "第一个场景",
    //       sceneId: "scene2",
    //     },
    //     {
    //       pitch: -10.8,
    //       yaw: 222.6,
    //       type: "scene",
    //       text: "第二个场景",
    //       sceneId: "scene3",
    //     },
    //   ],
    // };
    let name_arr = earthStore.panoramaurl.split("-");

    console.log(name_arr);

    if (name_arr.length > 3) {
      imgtime.value = name_arr[name_arr.length - 1].split(".")[0].split(",").join("-");
    }

    //根据中间图片的偏移角度计算周围图片的偏转角

    console.log(pannelviewer);
  }
}
</script>
<style lang="scss" scoped>
.panoramadiv {
  position: absolute;
  bottom: 80px;
  right: 100px;
  z-index: 6;
  width: 520px;
  height: 320px;
}
</style>
